<template>
  <div
    v-if="(!lazy || loaded) || show"
    v-show="show"
    class="ec-container">
    <div class="title">{{ infoTitle }}
      <el-tooltip
        v-if="infoTips"
        :content="infoTips"
        effect="dark"
        placement="top">
        <i class="wk wk-help wk-help-tips" />
      </el-tooltip>
    </div>
    <div class="option-bar">
      <el-tabs
        v-if="showOptions"
        v-model="optionsType"
        @tab-click="refreshList">
        <el-tab-pane
          v-for="item in options"
          :key="item.value"
          :label="item.name"
          :name="item.value">
          <template slot="label">
            <span>{{ item.name }}</span>
            <span
              v-if="item.num"
              style="position: absolute;top: 11px;"
              class="el-badge__content el-badge__content--primary">
              {{ item.num }}
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>
      <flexbox
        v-if="selectionList.length == 0"
        justify="space-between"
        class="selection-bar">
        <div>
          <el-select
            v-if="showSubType"
            v-model="isSubType"
            style="width: 200px;"
            mode="no-border"
            @change="refreshList">
            <el-option
              v-for="item in [{name: $t('crm.message.f9a99a25de6dde4ef54f5147d004c676'), value: 1}, {name: $t('crm.message.d5318943ed0121143ea78b797e5e6474'), value: 2}]"
              :key="item.value"
              :label="item.name"
              :value="item.value" />
          </el-select>
        </div>

        <div>
          <el-button
            v-if="showFilterView"
            type="subtle"
            class="filter-button"
            icon="wk wk-screening"
            @click="getFilterFieldInfo">
            {{ $t('crm.message.5d18bd4f72ea31f906ac893401dc0c19') }}
          </el-button>
          <el-button
            v-if="canAllMark"
            type="subtle"
            icon="wk wk-tag"
            @click="allMarkReadClick">
            {{ $t('crm.message.85a4c1f279bc49dd3893ca79cb058fa1') }}
          </el-button>
        </div>
      </flexbox>
      <flexbox v-else class="selection-bar">
        <div class="selected—title">
          {{ $t('crm.message.b7e85958dac6c4b8f7dfa681df3a5153') }}
          <span class="selected—count">{{ selectionList.length }}</span>
          {{ $t('crm.message.62336175fcc016c1237cafa8f9ce8d8c') }}
        </div>
        <flexbox class="selection-items-box">
          <el-button
            v-for="(item, index) in selectionButtonList"
            :key="index"
            :icon="item.icon"
            size="medium"
            @click="selectionBarClick(item.type)">
            {{ item.name }}
          </el-button>
        </flexbox>
      </flexbox>
    </div>
    <filter-content
      v-if="filterObj.form && filterObj.form.length > 0"
      :obj="filterObj"
      @delete="handleDeleteField" />
    <div v-loading="loading" style="position: relative;">
      <el-table
        id="crm-table"
        :data="list"
        :height="tableHeight"
        :cell-class-name="cellClassName"
        :class="WKConfig.tableStyle.class"
        :stripe="WKConfig.tableStyle.stripe"
        highlight-current-row
        style="width: 100%;"
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange">
        <el-table-column
          v-if="selectionButtonList.length > 0"
          show-overflow-tooltip
          fixed
          type="selection"
          align="center"
          width="55" />
        <el-table-column
          v-if="showCall"
          :resizable="false"
          prop="call"
          fixed
          label=""
          width="55">
          <template
            slot="header"
            slot-scope="{}">
            <i
              class="el-icon-phone"
              style="color: #2486e4;cursor: not-allowed; opacity: 0.5;" />
          </template>
          <template slot-scope="scope">
            <el-popover
              placement="right"
              width="500"
              popper-class="no-padding-popover"
              trigger="click"
              @show="showData(scope.row)"
              @hiden="showCount = -1">
              <call-center
                :scope="scope"
                :show="showCallCenter(scope.row)"
                :crm-type="rowType"
                @changeType="changeCRMType" />
              <el-button
                slot="reference"
                :style="{'opacity' :scope.$index >= 0 ? 1 : 0}"
                type="primary"
                class="wk-call-btn"
                icon="el-icon-phone"
                circle
                @click.stop="callCheckClick($event,scope,scope.$index)" />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="`column${index}`"
          :prop="item.field"
          :label="item.name"
          :min-width="item.width"
          show-overflow-tooltip>
          <template slot-scope="{ row, column }">
            <template v-if="item.field == 'dealStatus'">
              <span :class="row[item.field] | dealIcon" />
              <span>{{ row[item.field] | dealName }}</span>
            </template>
            <template
              v-else-if="item.field == 'status' && crmType === 'customer'">
              <i
                v-if="row.status == 2"
                class="wk wk-circle-password customer-lock" />
            </template>
            <template
              v-else-if="item.field == 'checkStatus' || item.field == 'examineStatus'">
              <span
                :style="getStatusStyle(row[item.field])"
                class="status-mark" />
              <span>{{ getStatusName(row[item.field]) }}</span>
            </template>
            <template v-else-if="item.field == 'invoiceType'">
              {{ fieldFormatter(row, column, row[column.property], item) }}
            </template>
            <wk-field-view
              v-else
              :props="item"
              :form-type="item.formType"
              :value="row[column.property]"
            >
              <template slot-scope="">
                {{ fieldFormatter(row, column, row[column.property], item) }}
              </template>
            </wk-field-view>
          </template>
        </el-table-column>
        <el-table-column
          v-if="canUpdateStatus"
          :resizable="false"
          :label="$t('crm.message.b55a642ae69a14a501cc9df84e9719f4')"
          fixed="right"
          width="210">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              size="medium"
              @click="examineClick(row)">审批</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="p-contianer">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size.sync="pageSize"
        :total="total"
        class="p-bar"
        background
        layout="prev, pager, next, sizes, total, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <filter-form
      :field-list="filterFieldList"
      :dialog-visible.sync="showFilter"
      :obj="filterObj"
      :props="filterFormProps"
      @filter="handleFilter" />

    <!-- 相关详情页面 -->
    <c-r-m-all-detail
      v-if="crmType !== 'examine'"
      :id="rowID"
      :visible.sync="showDview"
      :crm-type="rowType"
      :model-data="modelData"
      @handle="getList" />
    <!-- 列表操作 -->
    <examine-detail
      v-if="crmType === 'examine' && showDview"
      :id="rowID"
      :no-listener-class="['el-table__body']"
      class="d-view"
      @hide-view="showDview=false"
      @handle="getList" />

    <!-- 审批操作 -->
    <examine-handle
      v-if="examineHandleShow"
      :id="examineTypeId"
      ref="examineHandle"
      :show="examineHandleShow"
      :record-id="recordId"
      :examine-type="examineHandleInfo.data ? 'batch_audit' : `crm_${crmType}`"
      :flow-id="flowId"
      :status="examineHandleInfo.status"
      :props="examineHandleProps"
      :get-post-fields="getAuthFieldsParams"
      @close="examineHandleShow = false"
      @save="examinConfirm" />

    <!-- 创建 -->
    <c-r-m-all-create
      v-if="crmCreateShow"
      ref="crmAllCreate"
      :crm-type="createType"
      :props="createProps"
      :action="crmCreateAction"
      @close="crmCreateShow = false">
      <div slot="footer">
        <el-button
          type="success"
          @click="examineHandleClick(1)">通过</el-button>
        <el-button
          type="danger"
          @click="examineHandleClick(2)">拒绝</el-button>

      </div>
    </c-r-m-all-create>

    <!-- OA审批 -->
    <examine-create-view
      v-if="oaCreateShow"
      ref="oaAllCreate"
      :category-id="crmCreateAction.data ? crmCreateAction.data.categoryId : null"
      :type="crmCreateAction.data ? crmCreateAction.data.type : null"
      :action="crmCreateAction"
      :props="createProps"
      @hiden-view="oaCreateShow = false">
      <div slot="footer">
        <el-button
          type="success"
          @click="examineHandleClick(1)">通过</el-button>
        <el-button
          type="danger"
          @click="examineHandleClick(2)">拒绝</el-button>
      </div>
    </examine-create-view>
  </div>
</template>

<script>
import crmTypeModel from '@/views/crm/model/crmTypeModel'
import { filterIndexfieldsAPI } from '@/api/crm/common'
import { crmLeadsSetFollowAPI } from '@/api/crm/leads'
import { crmCustomerSetFollowAPI } from '@/api/crm/customer'
import {
  crmMessagAllDealAPI,
  crmMessagzealByIdAPI
} from '@/api/crm/message'
import { examineRecordBatchAuditAPI } from '@/api/examine'
import { examinesQueryAdvancedConfigAPI } from '@/api/examine'

import FilterForm from '@/components/Page/FilterForm'
import FilterContent from '@/components/Page/FilterForm/FilterContent'
import CRMAllDetail from '@/views/crm/components/CRMAllDetail'
import ExamineDetail from '@/views/oa/taskExamine/superExamine/Detail'
import WkFieldView from '@/components/NewCom/WkForm/WkFieldView'
import CRMAllCreate from '@/views/crm/components/CRMAllCreate'
import ExamineCreateView from '@/views/oa/examine/components/ExamineCreateView'

import CallCenter from '@/callCenter/CallCenter'
import MessageTableMixin from '../mixins/MessageTable'
import ExamineHandle from '@/components/Examine/ExamineHandle'
import FlowAuthFieldsMixin from '@/components/Examine/mixins/AuthFieldsMixin' // 审批流字段授权

export default {
  /** 客户管理 的待审核系统 */
  name: 'CRMMessage',

  components: {
    FilterForm,
    FilterContent,
    CRMAllDetail,
    ExamineDetail,
    CallCenter,
    WkFieldView,
    ExamineHandle,
    CRMAllCreate,
    ExamineCreateView
  },

  filters: {
    dealIcon(statu) {
      return statu == 1 ? 'deal-suc' : 'deal-un'
    },

    dealName(statu) {
      return statu == 1 ? window.app.$t('crm.message.a2cb3e3a7c660f2b7b39893865d017ee') : window.app.$t('crm.message.0c6cc54435a4c38c7fcbf31029e5d45f')
    }
  },

  mixins: [MessageTableMixin, FlowAuthFieldsMixin],

  props: {
    // crm类型
    crmType: {
      type: String,
      default: ''
    },
    // crm某个类型下的类型数据
    infoType: {
      type: String,
      default: ''
    },

    infoTitle: {
      type: String,
      default: ''
    },

    infoTips: {
      type: String,
      default: ''
    },

    // 表头
    infoHeads: Array,

    // 标示信息
    iconData: Object,

    // 展示的时候 才发请求
    show: Boolean,

    // 待办模块 用于 标记
    model: Number,
    lazy: Boolean
  },

  data() {
    return {
      optionsType: '0',
      options: [],
      isSubType: 1, // 是否是下属
      /** 高级筛选 */
      showFilter: false, // 控制筛选框
      filterFieldList: [],
      filterObj: { form: [] }, // 筛选确定数据
      /** 勾选数据操作 */
      selectionList: [], // 勾选的数据
      /** 控制详情展示 */
      rowID: '', // 行信息
      rowType: '', // 详情类型
      showDview: false,
      showCount: -1, // 储存客户id作为展示的标识
      modelData: {}, // 储存电话信息作为详情展示通话的依据
      loaded: false,
      // 审批
      examineHandleInfo: { status: 1 }, // 1 审核通过 2 审核拒绝 4 已撤回
      examineHandleProps: {
        setBackNodeShow: false
      }, // 审批操作配置项
      examineHandleShow: false, // 审核操作
      filterFormProps: {
        showExport: false, // 控制是否展示外露按钮
        showSaveScene: false
      },

      commonDetailAttrs: null,
      // 字段授权审批
      recordId: '',
      rowDetail: null,
      examineInfo: null, // 审批信息
      examineTypeId: '', // 业务id
      flowId: '',
      createType: '', // 创建类型
      authFields: [], // 字段授权
      createProps: null, // 创建配置
      crmCreateShow: false, // 展示创建
      oaCreateShow: false // OA展示创建
    }
  },
  computed: {
    // 展示勾选框
    showFollow() {
      if (this.infoType == 'followLeads' || this.infoType == 'followCustomer') {
        return this.optionsType == '1' // 待跟进
      }

      return false
    },

    // 操作按钮列表
    selectionButtonList() {
      const temps = this.showFollow ? [{
        name: this.$t('crm.message.0ac4dd6baeff105a38dc235a626cbd15'),
        type: 'follow',
        icon: 'wk wk-edit'
      }] : []

      if (this.canMark) {
        temps.push({
          name: this.$t('crm.message.30ebc3e367d91593a8ac88f3a119f9c0'),
          type: 'mark-deal',
          icon: 'wk wk-tag'
        })
      }

      if (this.canUpdateStatus) {
        temps.push({
          name: this.$t('crm.message.f4853260f7528d1571acb99a9a522c04'),
          type: 'examine-success',
          icon: 'wk wk-icon-success-line'
        })
        temps.push({
          name: this.$t('crm.message.640f940e8faf2adad7f040358965965b'),
          type: 'examine-reject',
          icon: 'wk wk-icon-close-line'
        })
      }
      return temps
    },

    // 是联系操作的选择项
    isContactOption() {
      return this.infoType == 'todayCustomer' ||
        this.infoType == 'todayBusiness' ||
        this.infoType == 'todayLeads'
    },

    // 展示筛选
    showFilterView() {
      if (this.crmType == 'receivablesPlan' ||
      this.crmType == 'examine') {
        return false
      }
      return true
    },

    // 展示审核状态
    showCheckStatus() {
      if (this.crmType == 'contract' || this.crmType == 'receivables') {
        return true
      }
      return false
    },

    // 展示客户池天数
    showPoolDay() {
      if (this.crmType == 'customer') {
        return true
      }
      return false
    },

    // 展示我的/下属筛选
    showSubType() {
      if (
        this.infoType == 'todayCustomer' ||
        this.infoType == 'todayBusiness' ||
        this.infoType == 'todayLeads' ||
        this.infoType == 'putInLeadsPoolRemind' ||
        this.infoType == 'putInPoolRemind' ||
        this.infoType == 'returnVisitRemind' ||
        this.infoType == 'followLeads' ||
        this.infoType == 'followCustomer'
      ) {
        return true
      }
      return false
    },

    /**
     * 能标记
     */
    canMark() {
      if (this.options.length) {
        if (this.showSubType && this.showOptions) {
          if (this.isContactOption) {
            return (this.optionsType == '1' || this.optionsType == '2') && this.isSubType == 1 // optionsType 2 逾期
          }
          return this.optionsType == '1' && this.isSubType == 1
        }

        if (this.showSubType) {
          return this.isSubType == 1 //  我的
        }

        if (this.showOptions) {
          return this.optionsType == '1'
        }
        return false
      }

      return true
    },

    // 能全部标记
    canAllMark() {
      // TODO 暂时 逾期不能进行全部比较操作，等后期后端增加接口
      if (this.isContactOption) return this.optionsType == '1'
      return this.canMark
    },

    // 权限
    showCall() {
      if (
        this.infoType == 'todayCustomer' ||
        this.infoType == 'followLeads' ||
        this.infoType == 'todayLeads' ||
        this.infoType == 'putInPoolRemind' ||
        this.infoType == 'followCustomer') {
        return this.$store.state.crm.isCall
      }
      return false
    },

    // 能进行审批
    canUpdateStatus() {
      if (
        this.infoType == 'checkContract' ||
        this.infoType == 'checkReceivables' ||
        this.infoType == 'checkInvoice' ||
        this.infoType == 'checkOaTypeIds') {
        return this.optionsType === '1' // 待审核
      }
      return false
    },

    // 是OA审批
    isOAExamine() {
      return this.model === 13
    },

    // 是CRM 审批
    isCRMExamine() {
      // 5 待审核合同 6 待审核回款 10 待审核发票
      return [5, 6, 10].includes(this.model)
    }
  },

  watch: {
    show: {
      handler() {
        if (this.show) {
          this.loaded = true
          this.initInfo()
        }
      },
      immediate: true
    }
  },

  methods: {
    /**
     * 进入初始化信息
     */
    initInfo() {
      this.options = this.getOption()

      if (this.showOptions && this.options.length > 0) {
        this.optionsType = this.options[0].value
      }

      // 固定表头
      if (this.infoHeads) {
        this.fieldList = this.infoHeads
      }

      this.initTableHead()
    },

    /**
     * 初始化表头数据
     */
    initTableHead() {
      this.currentPage = 1
      if (this.fieldList.length == 0) {
        this.getFieldList()
      } else {
        this.getList()
        this.$store.dispatch('GetMessageNum')
      }
    },

    /**
     * 刷新列表
     */
    refreshList() {
      this.list = []
      this.currentPage = 1
      if (this.fieldList.length > 0) {
        this.getList()
      } else {
        this.getFieldList()
      }
    },

    /**
     * 勾选数据
     */
    handleSelectionChange(val) {
      this.selectionList = val // 勾选的行
    },

    /**
     * 勾选后的操作
     */
    selectionBarClick(type) {
      if (type == 'follow') {
        this.$confirm(
          this.$t('crm.message.c8fd738305af5e0ae5b20102280bd23c'),
          this.$t('crm.message.0e302030010f7416d4577fac68a0df8b'),
          {
            confirmButtonText: this.$t('crm.message.fd63436c8be9ef03ced95125c94608b4'),
            cancelButtonText: this.$t('crm.message.c882e9003e3cce3b1129a8d6b98e7f82'),
            type: 'warning'
          }
        )
          .then(() => {
            const request = {
              followLeads: crmLeadsSetFollowAPI,
              followCustomer: crmCustomerSetFollowAPI
            }[this.infoType]
            request(
              this.selectionList
                .map(item => item[this.crmType + 'Id'])
            )
              .then(res => {
                this.$message.success(this.$t('crm.message.6f2d22714c0a60ffbfea71b5c5a73cce'))
                this.refreshList()

                this.$emit('on-handle', {
                  type: 'follow',
                  value: this.selectionList.length,
                  infoType: this.infoType
                })

                this.requestNumCount()
              })
              .catch(() => {})
          })
          .catch(() => {})
      } else if (type == 'mark-deal') {
        const params = { model: this.model }
        params.list = this.selectionList
          .map(item => {
            const temp = {}
            const fieldKey = `${this.crmType}Id`
            temp.typeId = item[fieldKey]
            // 待进入公海提醒 需要的公海id
            if (['putInPoolRemind', 'putInLeadsPoolRemind'].includes(this.infoType)) {
              temp.poolIds = item.poolIds
            }
            return temp
          })
        crmMessagzealByIdAPI(params).then(res => {
          this.$message.success(this.$t('crm.message.8801054155326d1ef470db26fb2d7b6f'))
          this.getList()
          this.requestNumCount()
        }).catch(() => {})
      } else if (type == 'examine-success') {
        this.examineHandleProps.setBackNodeShow = false
        this.examineHandleInfo.status = 1
        this.examineHandleInfo.data = this.selectionList
        this.examineHandleShow = true
      } else if (type == 'examine-reject') {
        this.examineHandleProps.setBackNodeShow = false
        this.examineHandleInfo.status = 2
        this.examineHandleInfo.data = this.selectionList
        this.examineHandleShow = true
      }
    },

    /**
     * 获取高级筛选字段数据后展示
     */
    getFilterFieldInfo() {
      filterIndexfieldsAPI({
        label: crmTypeModel[this.crmType]
      })
        .then(res => {
          this.filterFieldList = res.data || []
          this.showFilter = true
        })
        .catch(() => {})
    },

    /**
     * 选择筛选字段
     */
    handleFilter(form) {
      this.filterObj = form
      this.showFilter = false
      this.updateTableHeight()
      this.refreshList()
    },

    /**
     * 删除筛选字段
     */
    handleDeleteField(data) {
      this.filterObj = data.obj
      this.updateTableHeight()
      this.refreshList()
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (
        (column.property === 'name' && this.crmType != 'contract') ||
        (column.property === 'content' && this.crmType === 'examine') ||
        column.property === 'number' ||
        column.property === 'leadsName' ||
        column.property === 'customerName' ||
        column.property === 'businessName' ||
        column.property === 'contactsName' ||
        column.property === 'num' ||
        column.property === 'visitNumber' ||
        column.property === 'invoiceApplyNumber'
      ) {
        return 'can-visit--underline'
      } else {
        return ''
      }
    },

    /**
     * pover 显示时触发
     */
    showData(val) {
      if (
        this.infoType == 'todayCustomer' ||
        this.infoType == 'followCustomer' ||
        this.infoType == 'putInPoolRemind') {
        this.showCount = val.customerId
        this.rowType = 'customer'
      } else if (this.infoType == 'followLeads' || this.infoType == 'todayLeads') {
        this.showCount = val.leadsId
        this.rowType = 'leads'
      }
    },
    /**
       * 查看详情
       * @param val
       */
    changeCRMType(val) {
      this.rowType = val.type
      this.rowID = val.id

      this.modelData = {
        modelId: val.id,
        model: val.type
      }

      this.showDview = true

      let callOutData = {
        modelId: val.id,
        model: val.type
      }
      callOutData = JSON.stringify(callOutData)
      localStorage.setItem('callOutData', callOutData)
    },

    /**
     * 解决povper重复的bug
    */
    callCheckClick(e, scope) {
      this.list.forEach(item => {
        this.$set(item, 'callShow', false)
      })
      this.$set(scope.row, 'callShow', !scope.row.callShow)
      const popoverEl = e.target.parentNode
      popoverEl.__vue__.showPopper = !scope.row.callShow
    },

    /**
     * 展示呼出页面
     */
    showCallCenter(row) {
      if (
        this.infoType == 'todayCustomer' ||
        this.infoType == 'followCustomer' ||
        this.infoType == 'putInPoolRemind') {
        if (row.customerId === this.showCount) {
          return true
        }
      } else if (this.infoType == 'followLeads' || this.infoType == 'todayLeads') {
        if (row.leadsId === this.showCount) {
          return true
        }
      }
      return false
    },

    /**
     * 全部标记为已读
     */
    allMarkReadClick() {
      crmMessagAllDealAPI({
        model: this.model
      }).then(res => {
        this.$message.success(this.$t('crm.message.21f24423be7811239254566a7f5eab76'))
        this.requestNumCount()
        this.getList()
      }).catch(() => {})
    },

    /**
     * 获取option
     */
    getOption() {
      if (this.isContactOption) {
        return [
          { name: this.$t('crm.message.0f7ffeafc6e9e59ee72a916211ba0bb0'), value: '1', num: 0, isMenuNum: true },
          { name: this.$t('crm.message.93a663af5394fa3c0f1a5c620383315c'), value: '2', num: 0, key: 'overtime' },
          { name: this.$t('crm.message.4eb6d61659a0d2d6d5f489a6fcdecd18'), value: '3', num: 0 }
        ]
      } else if (
        this.infoType == 'followLeads' ||
        this.infoType == 'followCustomer'
      ) {
        return [{ name: this.$t('crm.message.daacccd1a5a241e842eef9cea46a78ff'), value: '1', num: 0, isMenuNum: true }, { name: this.$t('crm.message.4b2b52669e8a5dfeed6ec270ee1e8b8c'), value: '2', num: 0 }]
      } else if (
        this.infoType == 'checkContract' ||
        this.infoType == 'checkReceivables' ||
        this.infoType == 'checkInvoice' ||
        this.infoType == 'checkOaTypeIds'
      ) { // isList 读取列表返回数量
        return [{ name: this.$t('crm.message.c39c79af4e1ec33f347373fddaa2e770'), value: '1', num: 0, isList: true }, { name: this.$t('crm.message.62077c63c019b7fbd46f9e1cf8c51326'), value: '2', num: 0 }, { name: '抄送给我的', value: '3', num: 0 }]
      } else if (this.infoType == 'remindReceivablesPlan') {
        return [
          { name: this.$t('crm.message.275bcd992be751a9be630396ab374ec3'), value: '1', num: 0, isMenuNum: true },
          { name: this.$t('crm.message.3adfa42fb7f6351297f06ff82e98f279'), value: '2', num: 0 },
          { name: this.$t('crm.message.2aa6caa9a73c6040b8e0037677c239c0'), value: '3', num: 0, key: 'overtime' }
        ]
      } else if (this.infoType == 'endContract') {
        return [{ name: this.$t('crm.message.43cdf850b5158e3b82b1e41564471bea'), value: '1', num: 0, isMenuNum: true }, { name: this.$t('crm.message.d1a797f4e743f85c194e605aa7fa810f'), value: '2', num: 0 }]
      }

      return []
    },

    /**
     * 审批操作
     */
    /**
      * @description: 审批点击
      * @return {*}
      */
    async examineClick(row) {
      this.recordId = row.examineRecordId

      if (this.isCRMExamine) {
        this.createType = {
          5: 'contract',
          6: 'receivables',
          10: 'invoice'
        }[this.model]

        this.examineTypeId = row[`${this.createType}Id`] // 业务id

        const getFields = () => {
          return new Promise((resolve, reject) => {
            const detailRequest = this.flowGetCRMDetailRequestFun(this.createType)
            Promise.all([
              detailRequest(this.examineTypeId),
              examinesQueryAdvancedConfigAPI({ recordId: this.recordId })
            ])
              .then(res => {
                const [detailRes, flowRes] = res
                const resData = detailRes.data
                this.examineInfo = flowRes.data
                console.log('examineInfo', this.examineInfo)
                this.flowId = this.examineInfo.examineFlowId // 当前进行中的flowId
                //  5 合同 6 回款  10 发票  model
                const { label } = this.examineInfo

                const titleKey = {
                  1: 'num',
                  2: 'number',
                  3: 'invoiceApplyNumber'
                }[label]
                this.createProps.title = resData[titleKey]

                this.crmCreateAction.data = resData
                this.crmCreateAction.batchId = resData.batchId

                const crmLabel = {
                  5: 6,
                  6: 7,
                  10: 18
                }[this.model]
                this.flowGetAuthFields({
                  flowId: this.flowId,
                  examineId: this.examineInfo.examineId,
                  label: crmLabel, // CRM type
                  recordId: this.recordId
                }).then(res => {
                  this.authFields = res.data || []

                  // 校验batchId是否存在，如果不存在根据字段里的替换
                  if (!this.crmCreateAction.batchId &&
                  this.authFields.length > 0) {
                    this.crmCreateAction.batchId = this.authFields[0].batchId
                    this.crmCreateAction.data.batchId = this.authFields[0].batchId
                  }

                  resolve(this.authFields)
                }).catch(() => {
                  reject()
                })
              }).catch(() => {})
          })
        }

        this.createProps = {
          title: '',
          showConfirm: false,
          showCancel: false,
          getFields
        }

        this.crmCreateAction = {
          type: 'update',
          id: this.examineTypeId,
          data: null
        }
        this.crmCreateShow = true
      } else if (this.isOAExamine) {
        this.examineTypeId = row.examineId

        const getFields = () => {
          return new Promise((resolve, reject) => {
            Promise.all([
              this.flowGetOADetailRequestFun()(this.examineTypeId),
              examinesQueryAdvancedConfigAPI({ recordId: this.recordId })
            ])
              .then(res => {
                const [detailRes, flowRes] = res
                const resData = detailRes.data
                this.examineInfo = flowRes.data
                console.log('examineInfo', this.examineInfo)
                this.flowId = this.examineInfo.examineFlowId // 当前进行中的flowId

                this.createProps.title = resData.categoryTitle

                this.crmCreateAction.data = resData
                this.crmCreateAction.batchId = resData.batchId

                this.flowGetAuthFields({
                  flowId: this.flowId,
                  examineId: this.examineInfo.examineId,
                  label: 0, // CRM type
                  typeId: this.examineTypeId,
                  recordId: this.recordId
                }).then(res => {
                  this.authFields = res.data || []

                  // 校验batchId是否存在，如果不存在根据字段里的替换
                  if (!this.crmCreateAction.batchId &&
                  this.authFields.length > 0) {
                    this.crmCreateAction.batchId = this.authFields[0].batchId
                    this.crmCreateAction.data.batchId = this.authFields[0].batchId
                  }

                  resolve(this.authFields)
                }).catch(() => {
                  reject()
                })
              }).catch(() => {})
          })
        }

        this.createProps = {
          title: '',
          showConfirm: false,
          showCancel: false,
          getFields
        }

        this.crmCreateAction = {
          type: 'update',
          id: this.examineTypeId,
          data: null
        }
        this.oaCreateShow = true
      }
    },

    /**
     * 撤回审核 通过 拒绝
     */
    examineHandleClick(status) {
      console.log('examineHandle', status)
      const { isRejectChooseFlow } = this.examineInfo // 开启驳回节点配置
      this.examineHandleProps.setBackNodeShow = (isRejectChooseFlow && status == 2)
      this.examineHandleInfo.status = status
      this.examineHandleInfo.data = null // 仅批量审批时有值
      this.examineHandleShow = true
    },

    /**
     * @description: 获取授权post字段
     * @return {*}
     */
    getAuthFieldsParams() {
      // 仅在 ExamineInfoSection 组件内，该变量有值
      let createView = null
      if (this.isOAExamine) {
        createView = this.$refs.oaAllCreate
      } else if (this.isCRMExamine) {
        createView = this.$refs.crmAllCreate?.$refs.create
      }

      if (createView) {
        let mainLabel = null
        if (this.isOAExamine) {
          mainLabel = 0
        } else if (this.isCRMExamine) {
          mainLabel = {
            contract: 6,
            receivables: 7,
            invoice: 18
          }[this.createType] // 业务label
        }
        return this.flowGetAuthPostFields(mainLabel, this.authFields, createView, this.crmCreateAction.data)
      }
    },

    /**
     * 审批确定
     */
    examinConfirm(confirmData) {
      // 勾选批量审批的类型
      if (confirmData.examineType === 'batch_audit') {
        if (this.examineHandleInfo.data) {
          const examineHandleInstance = this.$refs.examineHandle
          examineHandleInstance.loading = true
          const { data, status } = this.examineHandleInfo
          examineRecordBatchAuditAPI({
            examineBOS: data.map(item => {
              return {
                typeId: item[`${this.crmType}Id`],
                recordId: item.examineRecordId,
                status: status,
                remarks: confirmData.content
              }
            })
          }).then(res => {
            examineHandleInstance.loading = false
            this.$message.success('操作成功')
            this.getList()
            this.requestNumCount()
            this.examineHandleShow = false
          }).catch(() => {
            examineHandleInstance.loading = false
          })
        }
      } else {
        this.$nextTick(() => {
          if (this.crmCreateShow) {
            this.crmCreateShow = false // 关闭编辑数据的弹框
          }
          if (this.oaCreateShow) {
            this.oaCreateShow = false // 关闭编辑数据的弹框
          }
        })

        this.requestNumCount()
        this.getList()
      }
    },

    /**
     * 待办事项
     */
    requestNumCount() {
      this.$store
        .dispatch('GetMessageNum')
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
@import "../../styles/table.scss";

/** 场景和筛选 */
.filtrate-button {
  display: inline-block;
  margin-left: 10px;
  cursor: pointer;

  &-img {
    width: 12px;
    margin: 0 5px;
    vertical-align: middle;
  }
}

.filtrate-button:hover {
  color: $--color-primary;
}

.ec-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 24px 24px 0;
  overflow: hidden;
}

.title {
  font-size: 24px;

  .wk-help {
    margin-left: 5px;
    font-size: 16px;
  }
}

.option-bar {
  padding: 16px 0 8px;

  // .el-tabs {
  //   width: 280px;
  //   ::v-deep .el-tabs__header {
  //     margin: 0;
  //     .el-tabs__nav-wrap::after {
  //       display: none;
  //     }
  //   }
  // }

  // .el-badge {
  //   line-height: initial;
  // }
}

/** 勾选操作 */
.selection-bar {
  min-height: 34px;

  .selected—title {
    flex-shrink: 0;
    padding-right: 20px;
    font-weight: $--font-weight-semibold;

    .selected—count {
      color: $--color-primary;
    }
  }
}

.selection-items-box {
  padding: 0 15px;
  overflow-x: auto;
  overflow-y: hidden;

  ::v-deep .el-button {
    i {
      margin-right: 5px;
    }
  }
}

.el-button--primary.is-plain {
  background-color: white;
}

.el-button--primary.is-plain:focus,
.el-button--primary.is-plain:active,
.el-button--primary.is-plain:hover {
  color: $--color-primary;
}
</style>
